<template>

  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="70%" @ok="handleSubmit"
    @visible-change="visibleChange" :cancel-button-props="{ style: 'display: none' }" okText="关闭">
    <div>
      <a-row>
        <a-col span="12">
          <BasicForm autoFocusFirstItem style="min-height: 250px" @register="registerForm">
            <template #addData="{}">
              <a-button :onclick="addFormData" type="primary">
                {{ buttonText }}
              </a-button>
            </template>

            <template #select="{ model, field }">
              <JSearchSelect placeholder="请选择地块" :onChange="change" v-model:value="model[field]" dict="t_plot,name,id">
              </JSearchSelect>
            </template>
          </BasicForm>

          <div v-if="tableChose" class="" style="height: 300px;padding: 10px 6px 0;">
            <div ref="chartRef" style="width: 100%; height: 100%;"></div>
          </div>

        </a-col>
        <a-col span="12">
          <AMapComp :polygons="polygons" :onlyShow="true" class="flex-grow h-full" />
        </a-col>
      </a-row>
    </div>

    <div>
      <!--引用表格-->
      <BasicTable id="basicTable" @register="registerTable" @selection-change="handleSelectionChange"
        :rowSelection="{ type: 'radio' }">

        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
    </div>

  </BasicModal>
</template>

<script lang="ts" setup>


import { ref, computed, unref, watch, toRaw, watchEffect } from 'vue';
import { BasicTable, useTable, TableAction, SorterResult } from '/@/components/Table';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { columns, formSchema, searchFormSchema } from '../TGrowPlan.data';
import { getExportUrl, getImportUrl, list, saveOrUpdate, saveBatchOrUpdate, deleteOne } from '../TGrowPlan.api';
import AMapComp from '/@/components/AMap/AMap.vue'
import dayjs from "dayjs";
import { useListPage } from "/@/hooks/system/useListPage";
import JSearchSelect from "/@/components/Form/src/jeecg/components/JSearchSelect.vue";
import { defHttp } from "/@/utils/http/axios";
import { useECharts } from '/@/hooks/web/useECharts';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const showCancelBtn = ref(false);
const datas = ref([]);
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
  // fieldMapToTime: [
  //   ['planTime', ['startTime', 'stopTime'], 'YYYY-MM-DD'],
  //   ['actualTime', ['actualStartTime', 'actualStopTime'], 'YYYY-MM-DD']],
  //labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 }
});
// 地图显示数据
const polygons = ref([]);
// 计划id
const planId = ref(null);
// 是否新增或者修改了数据
const isUpdateData = ref(false);
// 是否选择了表格数据修改
const tableChose = ref(false);
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  // console.log(data)
  //重置表单
  await resetFields();
  setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter, });
  if (data.record && data.record.planId) {
    planId.value = data.record.planId;
  }
  isUpdate.value = !!data?.isUpdate;
  // 防止上次编辑对新增造成影响
  if (!isUpdate.value) {
    planId.value = null;
  }
  tableChose.value = false;

  if (data.plotId) {
    //表单赋值
    await setFieldsValue({
      plotId: data.plotId
    });
    // 重新选择地块
    change(data.plotId)
  }

  // 总是重置地图数据，防止上次打开事件的影响
  // polygons.value = [];
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter })
  datas.value = [];
  if (isUpdate.value) {
    // 获取表格的数据
    getDatas();
  }
});
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
// 表单按钮的值
const buttonText = computed(() => (unref(tableChose) ? '点此修改' : '新增'));
//注册table数据
const { tableContext } = useListPage({
  tableProps: {
    dataSource: datas,
    columns: [
      {
        title: '产品',
        align: "center",
        dataIndex: 'productNo_dictText'
      },
      {
        title: '地块',
        align: "center",
        dataIndex: 'plotId_dictText'
      },

      {
        title: '计划开始时间',
        align: "center",
        dataIndex: 'startTime',
        customRender: ({ text }) => {
          return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
        },
      },
      {
        title: '计划结束时间',
        align: "center",
        dataIndex: 'stopTime',
        customRender: ({ text }) => {
          return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text)
        },
      },
      {
        title: '责任人',
        align: 'center',
        dataIndex: 'responsiblePerson'
      },
    ],
    canResize: false,
    useSearchForm: false,
    showTableSetting: false,
    formConfig: {
      //labelWidth: 120,
      // schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: []
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
  },
})

const [registerTable, { reload, setSelectedRowKeys }, { rowSelection, selectedRowKeys }] = tableContext
// 添加表单数据
async function addFormData(v) {
  try {
    let values = await validate();
    // console.log(values)
    // todo 只能说写的极其丑陋
    if (values.planTime) {
      let datesArray = values.planTime.split(',');
      if (!dayjs(datesArray[0], 'YYYY-MM-DD', true).isValid()) {
        values.startTime = dayjs(datesArray[0] + datesArray[1]).format('YYYY-MM-DD');
        values.stopTime = dayjs(datesArray[2] + datesArray[3]).format('YYYY-MM-DD')
      } else {
        let datesArray = values.planTime.split(',');
        values.startTime = datesArray[0]
        values.stopTime = datesArray[1]
      }
    }
    if (values.actualTime) {
      let datesArray = values.actualTime.split(',');
      if (!dayjs(datesArray[0], 'YYYY-MM-DD', true).isValid()) {
        values.actualStartTime = dayjs(datesArray[0] + datesArray[1]).format('YYYY-MM-DD');
        values.actualStopTime = dayjs(datesArray[2] + datesArray[3]).format('YYYY-MM-DD')
      } else {
        let datesArray = values.actualTime.split(',');
        values.actualStartTime = datesArray[0]
        values.actualStopTime = datesArray[1]
      }
    }
    if (planId.value) {
      values.planId = planId.value;
    }
    // 此处可以看前端有转义的方法没 todo
    defHttp
      .get({
        url: `/sys/dict/loadDict/t_product,name,no`,
        params: { pageSize: 1000, keyword: values.productNo },
      }).then((res) => {
        if (res) {
          values.productNo_dictText = res[0].label;
        }
      }).finally(() => {
        defHttp.get({
          url: `/sys/dict/loadDict/t_plot,name,id`,
          params: { pageSize: 1000, keyword: values.plotId },
        }).then((res) => {
          if (res) {
            values.plotId_dictText = res[0].label;
          }
        }).finally(() => {
          // 假设values是要添加的对象
          let existingIndex = datas.value.findIndex(item => item.id === values.id);
          // console.log(existingIndex);

          if (existingIndex >= 0 && values.id) {
            // 如果已存在具有相同id的元素，替换它
            datas.value[existingIndex] = values;
          } else {
            // 如果不存在，添加到数组中
            datas.value.push(values);
          }

        })
      })
  } finally {
  }
}
//表单提交事件
async function handleSubmit(v) {
  try {
    //提交表单
    await saveBatchOrUpdate(datas.value, tableChose.value).then((res) => {
      if (res && res.id) {
        planId.value = res.id;
      }
      //刷新列表
      reload();
      // 标准已经有数据的更新
      isUpdateData.value = true;
    });
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
// 对话框打卡或关闭事件
async function visibleChange(e) {
  //刷新列表
  if (!e && isUpdateData.value) {
    emit('success');
  }
}
const chartRef = ref<HTMLDivElement | null>(null);
// 获取生长周期时间节点
const getGrowthcycleRatio = (e) => {
  defHttp.get({ url: "/productGrowthcycle/getGrowthcycleRatio", params: e }).then(res => {
    // console.log(res)
    if (res && res.length > 0) {
      const { setOptions, echarts } = useECharts(chartRef as Ref<HTMLDivElement>);
      let xAxis = [];
      let series = [];
      let daycount = 0;
      res.map(item => {
        xAxis.push(item.growthcycleName.slice(0, -1))
        daycount += item.days;
        let endTime = item.endTime.split('-')
        endTime.shift();
        series.push({ value: daycount, label: endTime.join('-'), content: item.growthcycleMemo });
      })
      const mapOption = {
        xAxis: {
          type: 'category',
          data: xAxis
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 天'   //添加单位
          }
        },
        series: [
          {
            data: series,
            type: 'line',
            label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                return params.data.label;
              }
            }
          }
        ],
        tooltip: {
          show: true,
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            return params[0].data.content;
          }
        }
      };
      // console.log(mapOption)
      mapOption && setOptions(mapOption);
    }
  });
}

// 表格选择事件
const handleSelectionChange = async ({ keys, rows }) => {
  datas.value.map(async (item) => {
    if (item.id == keys) {
      // 在这里处理表格变化事件
      item.planTime = [item.startTime, item.stopTime];
      item.actualTime = [item.actualStartTime, item.actualStopTime];
      //表单赋值
      await setFieldsValue({
        ...item,
      });
      // 重新选择地块
      change(item.plotId)
      getGrowthcycleRatio({
        productNo: item.productNo,
        startTime: item.startTime,
        endTime: item.stopTime
      })
      tableChose.value = true;
    }
  })
};
// 表单选择地块事件
async function change(e) {
  defHttp.get({ url: "/plot/list", params: { id: e } }).then(res => {
    if (res && res.records && res.records.length > 0) {
      polygons.value = [JSON.parse(res.records[0].polygon)];
    }
  });

}
/**
* 成功回调
*/
function handleSuccess() {
  getDatas();
}
// 获取表格的数据
function getDatas() {
  // 获取表格的数据
  list({ "planId": planId.value, "pageSize": 10000 }).then((res) => {
    if (res && res.records) {
      datas.value = res.records;
      setSelectedRowKeys([res.records[0].id]);
      // handleSelectionChange({keys: res.records[0].id, rows: res.records});
    }
  })
}
/**
  * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
  * 操作栏
*/
function getTableAction(record) {
  if (!record.id) {
    return [];
  }
  return [
    {
      label: '删除',
      onClick: handleDelete.bind(null, record),
    }
  ]
}


</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%
}

:deep(.ant-calendar-picker) {
  width: 100%
}
</style>
